package com.lxb.myforum.service


import java.util.Date

import com.lxb.myforum.base.BaseService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Service

import com.lxb.myforum.pojo.Menu
import com.lxb.myforum.repository.MenuRepository
import com.lxb.myforum.service.spec.MenuSpec

@Service
class MenuService @Autowired
constructor(@param:Qualifier("menuRepository") private val menuRepository: MenuRepository) : BaseService() {

    fun findAll(menu: Menu, pageable: PageRequest): Page<Menu> {
        return menuRepository.findAll(MenuSpec(menu), pageable)
    }

    fun findAll(menu: Menu): List<Menu> {
        return menuRepository.findAll(MenuSpec(menu))
    }

    fun findById(id: Long): Menu {
        return menuRepository.findById(id).orElse(null)
    }

    fun findByPId(pId: Long): List<Menu> {
        val authorities = SecurityContextHolder.getContext().authentication.authorities
        println("authorities: " + authorities.toString())
        return menuRepository.findByParentId(pId)
    }

    fun save(menu: Menu): Menu? {
        var pMenu: Menu? = null

        if (menu.id == null) { // 说明是新增
            menu.createTime = Date()
            // 修改父dict的状态
            if(menu.parentId != null) {
                pMenu = menuRepository.findById(menu.parentId!!).orElse(null)
                // 如果存在父节点，那么修改一下父节点的信息
                if (pMenu != null) {
                    pMenu.isParent = true
                    pMenu.updateTime = Date()
                }
            }
        }

        menu.updateTime = Date() // 更新时间一直在变的
        val tmpMenu = menuRepository.save(menu)
        // 更新父节点
        if (pMenu != null) {
            menuRepository.save(pMenu)
        }
        return tmpMenu
    }
}
